/**
 * 新增履历
 * 工程项目名称：青州市民卡核心系统
 * 方法名：卡应用
 * 版本： ver 1.0  初版
 * 创建日期：20190319
 * 创建人：惠国磊
 */

var appFlag = {"公交应用":["3F01","M1BK"],"图书馆应用":["TSYY"]};
//对应下标的应用
var appClassification = ["图书馆应用","公交应用"];

function loadAppFlag(){
	var selectedValue = $("#appClassifyByAddNew").val();
	var selectApp = $("select[name='appKindId'] option[value='"+selectedValue+"']").html();
	var appFlagArray = appFlag[selectApp];
	var optionContent = "";
	if(appFlagArray){
		$.each(appFlagArray,function(index,item){
			optionContent += "<option value='"+item+"'>"+item+"</option>";
		})
	}
	$("#appFlagByAddNew").html(optionContent);
}
function queryAppDefinition(json){
	var content="";
	var item = json.dPage;
	var numPerPage=item.numPerPage;
	var currentPage=item.currentPage;
	var totalCount=item.totalCount;
	var onePageCount = [numPerPage*[currentPage-1]];
	var param = "";
	
	var list=item.list;
	if(list.length==0){
		content+="<tr><td colspan='8' align='center' >未查询到数据</td></tr>"
	}else{
		for(var i=0;i<list.length;i++){
			var value=list[i].appType;
			//alert("checkBox-value==>"+value);
			content+="<tr align='center'>"
					 +"<td><input name='appKindDefType' value="+value+" type='radio'></td>"
					 +"<td>"+eval(i+1+parseInt(onePageCount))+"</td>"
				     +"<td>"+list[i].appName+"</td>"
				     +"<td>"+list[i].appKindName+"</td>"
				     +"<td>"+list[i].isActive+"</td>"
				     +"<td>"+list[i].isAnnual+"</td>"
				     +"<td>"+list[i].lastOperator+"</td>"
				     +"<td>"+list[i].lastDate+"</td>"
				     +"<td>"+"<a href='applicationDefinition/modifyAppKind' weight='900' height='500' target='dialog' rel='更多信息' appType='"+value+"' pageFlag='detail'>"+"MORE……"+"</a></td>"
				     +"</tr>"
		}
		
	}
	$("#tdInfoByAppDef").html(content);
	$("input[name='numPerPage']").val(numPerPage);
	$("input[name='pageNum']").val(currentPage); 
	$("#totalCountByAppDef").text("条，共"+totalCount+"条");
	$("#paginationByAppDef").addClass("pagination").attr("targetType","navTab").attr("totalCount",totalCount).attr("numPerPage",numPerPage).attr("pageNumShown","10").attr("currentPage",currentPage).attr("rel","tdInfoByAppDef").attr("callback","queryAppDefinition");
	
	$("div.pagination").each(function(n,item){
		var $this = $(this);
		$this.pagination({
			targetType:"navTab",
			rel:"tdInfoByAppDef",
			totalCount:totalCount,
			numPerPage:numPerPage,
			pageNumShown:10,
			currentPage:currentPage,
			callback:queryAppDefinition
		});
	});
	
	var $p = $("#tableInfoByAppDef");
	initUI($p);
}


function getAppKindInfoByModify(json){
	var sign = json.sign;
	var appKindObj = json.appKind;
	if(sign=="modify"){
		var appFlagSelect = "<option value='"+appKindObj.appFlag+"'>"+appKindObj.appFlag+"</option>";
			//应用类型
			$("#appTypeByAddNew").val(appKindObj.appType);
			//应用名称
			$("#appKindNameByAddNew").val(appKindObj.appName).attr("readonly","readonly");
			//应用分类
			$("select[name='appKindId']").val(appKindObj.appKindId).attr("disabled","disabled");
			//应用类型状态
			$("#appTypeStatusByAddNew").val(appKindObj.isActivate);
			//有效期月数
			$("#validMonthByAddnew").val(appKindObj.validMonthNum);
			//是否需要年检
			$("#isAnnualByAddNew").val(appKindObj.isAnnual);
			//是否可停用
			$("#allowDisableByAddNew").val(appKindObj.allowDisable);
			//年审提前天数
			$("#annualAheadDays").val(appKindObj.annualAheadDays);
			//创建柜员号
			$("#crtOperatorByAddNew").val(appKindObj.crtOperator);
			//创建日期
			$("#crtDateByAddNew").val(getDate(appKindObj.crtDate));
			//最后修改柜员
			$("#lastOperator").val(appKindObj.lastOperator);
			//最后修改日期
			$("#lastModDate").val(getDate(appKindObj.lastDate));
			//备注
			$("#descriptionByAddNew").val(appKindObj.remark);
			//应用标识
			$("#appFlagByAddNew").html(appFlagSelect).attr("disabled","disabled");
			
			//修改按钮action
			var url = "applicationDefinition/updateAppDefToDB";
			$("#submitAppKind").attr("action",url);
	
	}
	if(sign=="detail"){
		var appFlagSelect = "<option value='"+appKindObj.appFlag+"'>"+appKindObj.appFlag+"</option>";
		//应用类型
		$("#appTypeByAddNew").val(appKindObj.appType).attr("disabled","disabled");
		//应用名称
		$("#appKindNameByAddNew").val(appKindObj.appName).attr("disabled","disabled");
		//应用分类
		$("select[name='appKindId']").val(appKindObj.appKindId).attr("disabled","disabled");
		//应用类型状态
		$("#appTypeStatusByAddNew").val(appKindObj.isActivate).attr("disabled","disabled");
		//应用标识
		$("#appFlagByAddNew").html(appFlagSelect).attr("disabled","disabled");
		//有效期月数
		$("#validMonthByAddnew").val(appKindObj.validMonthNum).attr("disabled","disabled");
		//是否需要年检
		$("#isAnnualByAddNew").val(appKindObj.isAnnual).attr("disabled","disabled");
		//是否可停用
		$("#allowDisableByAddNew").val(appKindObj.allowDisable).attr("disabled","disabled");
		//年审提前天数
		$("#annualAheadDays").val(appKindObj.annualAheadDays).attr("disabled","disabled");
		//创建柜员号
		$("#crtOperatorByAddNew").val(appKindObj.crtOperator).attr("readonly","readonly");
		//创建日期
		$("#crtDateByAddNew").val(getDate(appKindObj.crtDate)).attr("disabled","disabled");
		//最后修改柜员
		$("#lastOperator").val(appKindObj.lastOperator).attr("disabled","disabled");
		//最后修改日期
		$("#lastModDate").val(getDate(appKindObj.lastDate)).attr("disabled","disabled");
		//备注
		$("#descriptionByAddNew").val(appKindObj.remark).attr("disabled","disabled");
		
		
		$("span[name='requiredSpan']").attr("style","display:none");
		$(".formBar").attr("style","display:none");
	//	var $p = $("#submitAppKind");
	//	initUI($p);
	}
}

function getAppOpenInfo(json){
	var appOpenObjList = json.appOpenInfoObj;
	var contentToOpen = "";
	var contentToClose = "";
	var toOpenIndex = 0;
	var toCloseIndex = 0;
	for(var i=0;i<appOpenObjList.length;i++){
		var appOpenStatus = appOpenObjList[i].appStatus;
		var allowDisable = appOpenObjList[i].allowDisable;
		var openHtml = "";
		var rechargeHtml = "";
		if(allowDisable==1){
			openHtml = "<td><input type='submit' value='关闭' onclick='return closeAppRegister(this)'/></td>";
		}else{
			openHtml = "<td>--</td>";
		}
		//1.已开通
		if(appOpenStatus==1){
			toOpenIndex = parseInt(toOpenIndex) + 1;
			//如果是自行车，需要查询除余额，然后显示
			//其他应用暂时取消--
			var balance = "";
			var citizenCardNo = appOpenObjList[i].citizenCardNo;
			if(appOpenObjList[i].appFlag=="M1BK"){
				 $.post("business/getBikeBlance",{"citizenCardNo":citizenCardNo},function(json){
					 if(json.statusCode==DWZ.statusCode.error){
						 navTabAjaxDone(json)
					 }else{
						 if(json.head.rsltcode=="0000"){
							 var oldblance=json.body.balance;
							 vipno=json.body.vipno;
							 vipcardsn=json.body.vipcardsn;
							 balance=parseInt(oldblance)==0?0:parseInt(oldblance)/100
						 }else{
							 checkBikeError(json.head.rsltcode);
						 }	
					 }
				 },"json");
				 rechargeHtml="<td><input name='balanceByM1BK' id='balanceByM1BK' value='"+balance+"' size='10' readonly='readonly'/>"
				 			 +"</td>";
			 }else{
				rechargeHtml="<td>--</td>";
			}
			
			contentToClose+= "<tr align='center'>"
						+"<td>"+toOpenIndex+"</td>"
						+"<td>"+appOpenObjList[i].appName+"</td>"
						+"<td>"+appOpenObjList[i].appKindName+"</td>"
						+"<td><input name='appOpenFee' size= '10' readonly='readonly' value='"+(appOpenObjList[i].appFee).toFixed(2)+"'/></td>"
						+rechargeHtml
						+openHtml
						+"<td style='display:none;'><input name='hiddenAppType' value='"+appOpenObjList[i].appType+"'/></td>"
						+"<td style='display:none;'><input name='hiddenCitizenCardNo' value='"+appOpenObjList[i].citizenCardNo+"'/></td>"
						+"<td style='display:none;'><input name='hiddenAppFlag' value='"+appOpenObjList[i].appFlag+"'/></td>"
						+"</tr>"
		}else if(appOpenStatus==0){
			toCloseIndex = parseInt(toCloseIndex) + 1;
			//如果是自行车，需要加入充值金额的输入框
			//其他应用暂时取消--
			if(appOpenObjList[i].appFlag=="M1BK"){
				rechargeHtml="<td><select name='rechargeByM1BK' id='rechargeByM1BK'>"
							+"<option value='0'>0</option>"
							+"<option value='30'>30</option>"
						    +"<option value='50'>50</option>"
		                    +"<option value='100'>100</option>"
		                    +"<option value='500'>500</option>"
							+"</select>"
							+"</td>"
			}else{
				rechargeHtml="<td>--</td>"
			}
			contentToOpen+= "<tr align='center'>"
						+"<td>"+toCloseIndex+"</td>"
						+"<td>"+appOpenObjList[i].appName+"</td>"
						+"<td>"+appOpenObjList[i].appKindName+"</td>"
						+"<td><input name='appOpenFee' size= '10' readonly='readonly' value='"+(appOpenObjList[i].appFee).toFixed(2)+"'/></td>"
						+rechargeHtml
						+"<td><input type='submit' value='开通' onclick='return openAppRegister(this)'/></td>"
						+"<td style='display:none;'><input name='hiddenAppType' value='"+appOpenObjList[i].appType+"'/></td>"
						+"<td style='display:none;'><input name='hiddenCitizenCardNo' value='"+appOpenObjList[i].citizenCardNo+"'/></td>"
						+"<td style='display:none;'><input name='hiddenAppFlag' value='"+appOpenObjList[i].appFlag+"'/></td>"
						+"</tr>"
		}
	}
	$("#tdInfoByAppToOpen").html(contentToOpen);
	$("#tdInfoByAppToClose").html(contentToClose);
	var $p1 = $("#tableInfoByAppToOpen");
	var $p2 = $("#tableInfoByAppToClose");
	initUI($p1);
	initUI($p2);
}


function initBikeCardData(item){
	var appFlag = item.appFlag;
	var citizenCardNo = item.citizenCardNo;
	console.log("appFlag==>"+appFlag);
	console.log("citizenCardNo==>"+citizenCardNo);
	if(appFlag=="M1BK"){
		//写卡:初始化数据
		var flag=true;
		var findM1Flag = findLogicCard();
		if(findM1Flag){
			var cardsnInfo = readBlockExternal(initKey,0,0,0);
			var cardsn = cardsnInfo.substring(0,8);
			var writeInfo = citizenCardNo.substr(0, 2)=="11"?initBlock3:initBlock3_2;
			$("input[name='cardsnByOpenApp']").val(cardsn);
			var params = {"citizenCardNo":citizenCardNo};
			//发送后台请求数据库密钥
			$.ajax({
				type: 'POST',
				url:"appOpenReg/getBikeAppPWInfo",
				dataType:"json",
				data:params,
				async: false,
				success:function(json){
					if(json.statusCode==DWZ.statusCode.ok){
						var keys=json.key;
						var data=initInfo;
				//		var writeInfo = initBlock3;
						if(keys.length>0){
							//内容格式化
								for(var i=0;i<keys.length;i++){
									var sector=parseInt(keys[i].no)
										//写扇区(模式0)
										var ff= writeSectorExternal(keys[i].keya,sector,0,data);
										if(!ff){
											alertMsg.warn("自行车应用M1写扇区失败");
											checkError(getError());
											flag=false;
											return false;
										}
								}
								for(var i=0;i<keys.length;i++){
									//格式化扇区密钥(模式4)
									var sector=parseInt(keys[i].no)
								//	var writeInfo=keys[i].keya+keys[i].contrlword+keys[i].keyb;
									console.log("keys[i].keya==>"+keys[i].keya);
									var f= WriteBlockExternal(keys[i].keya,sector,sector*4+3,0,writeInfo);
									if(!f){
										alertMsg.warn("自行车应用M1格式化扇区失败");
										checkError(getError());
										flag=false;
										return false;
									}
								}
							}
							
					}else{
						navTabAjaxDone(json)
					}					
				},
				error: DWZ.ajaxError
			})	
			//终止提交
			if(!flag){
				return false;
			}
			if(flag){
				$("#pagerFormByCloseApp").attr("action","appOpenReg/closeBikeAppRegister");
				$("#pagerFormByCloseApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
			}
		}else{
			checkError(getError());
			return false;
		}
	}
	return flag;
}


function closeAppRegister(obj){
	var $this = $(obj);
	var $tr = $this.parent().parent().parent();
	var citizenCardNo = $tr.find("td").eq(7).find("input").val();
	$("input[name='citizenCardNoByCloseApp']").val(citizenCardNo);
	var appType = $tr.find("td").eq(6).find("input").val();
	$("input[name='appTypeByCloseApp']").val(appType);
	var appFlag = $tr.find("td").eq(8).find("input").val();
	$("input[name='appFlagByCloseApp']").val(appFlag);
	var deposit = $tr.find("td").eq(3).find("input").val();
	$("input[name='depositByCloseApp']").val(deposit);
	console.log("deposit==>"+deposit);
	var balance = $("input[name='balanceByM1BK']").val();
	$("input[name='blanceByCloseApp']").val(balance);
	console.log("balance==>"+balance);
	if(appFlag=="M1BK"){
		$("#pagerFormByCloseApp").attr("action","appOpenReg/closeBikeAppRegister");
		$("#pagerFormByCloseApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
	}
	if(appFlag=="3F01"){
		//写卡擦出数据
		var updateInfoA;
		if(appFlag=="3F01"){
			//需要修改appid状态码
			updateInfoA="key_appid,01|key_sdate,|key_edate,|key_cardtype,";
			blnRs=updateBaseInfo(appFlag,updateInfoA);//0015
			if(!blnRs){
				checkError(getError());
				return false;
			}
		$("#pagerFormByCloseApp").attr("action","appOpenReg/closeBusAppRegister");
		$("#pagerFormByCloseApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
	  }
	}
	if(appFlag=="TSYY"){
		$("#pagerFormByCloseApp").attr("action","appOpenReg/closeLibAppRegister");
		$("#pagerFormByCloseApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
	}
}

//ajax调用后台处理开通应用
function openAppRegister(obj){
	
	var $this = $(obj);
	//取得卡号，appType发送到后台处理
	var $tr = $this.parent().parent().parent();
	var citizenCardNo = $tr.find("td").eq(7).find("input").val();
	//console.log("citizenCardNo==>"+citizenCardNo);
	$("input[name='citizenCardNoByOpenApp']").val(citizenCardNo);
	var appType = $tr.find("td").eq(6).find("input").val();
	//console.log("appType==>"+appType);
	$("input[name='appTypeByOpenApp']").val(appType);
	var appFlag = $tr.find("td").eq(8).find("input").val();
	//console.log("appFlag==>"+appFlag);
	$("input[name='appFlagByOpenApp']").val(appFlag);
	var deposit = $tr.find("td").eq(3).find("input").val();
	//console.log("deposit==>"+deposit);
	$("input[name='depositByOpenApp']").val(deposit);
	var recharge = $tr.find("td").eq(4).find("select").val();
	//console.log("recharge==>"+recharge);
	if(!isNaN(parseInt(recharge))){
		$("input[name='rechargeByOpenApp']").val(recharge);
	}
	var sdata="";
	var operatorNo="";
	//卡主类型16进制
	var key_cardTypeA=cardPcodeToHex($("select[name='cardPNameByAppOpen']").val());
	$.ajax({
		type: 'POST',
		url:"getOperator",
		dataType:"json",
		async: false,
		success: function(json){
			operatorNo=json.userNo;
		},
	})
	var idate=writeDate(Date.now())
	sdata="key_cardTypeA,"+key_cardTypeA+"|key_idate,"+idate+"|key_operator,"+operatorNo;
	/*var blnRs=updateInfo_3F00(sdata)//写3F00
	if(!blnRs){
		checkError(getError());
		return false;
	}*/
	
	var customerNameGBK=writeName($URL.encode($("input[name='customerNameByAppOpen']").val()));
	var paperNo=writePaperNo($("input[name='paperNoByAppOpen']").val());
	var paperType=$("select[name='paperTypeByAppOpen']").val();
	var blnRs;
	var updateInfoA,updateInfoB;
	if(appFlag=="3F01"){
		updateInfoA="key_appid,02|key_sdate,"+idate+"|key_edate,"+afterDate(2)+"|key_cardtype,"+key_cardTypeA;
		updateInfoB="key_name,"+customerNameGBK+"|key_certificationNo,"+paperNo+"|key_certificationType,"+paperType;
		blnRs=updateBaseInfo(appFlag,updateInfoA);//0015
		if(!blnRs){
			checkError(getError());
			return false;
		}
		blnRs=updatePersonInfo(appFlag,updateInfoB);//016
		if(!blnRs){
			checkError(getError());
			return false;
		}
		//console.log("updateInfoA==>"+updateInfoA);
		//console.log("updateInfoB==>"+updateInfoB);
		$("#pagerFormByOpenApp").attr("action","appOpenReg/openBusAppRegister");
		$("#pagerFormByOpenApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
	}
	if(appFlag=="3F02"){
		updateInfoA="key_appid,02|key_sdate,"+idate;
		blnRs=updateBaseInfo(adf,updateInfoA);//0015
		if(!blnRs){
			checkError(getError());
			return false;
		}
	}
	if(appFlag=="3F10"){
		updateInfoB="key_name,"+customerNameGBK+"|key_certificationNo,"+paperNo+"|key_certificationType,"+paperType
		blnRs=updatePersonInfo(adf,updateInfoB);//0016
		if(!blnRs){
			checkError(getError());
			return false;
		}
	}
	if(appFlag=="9A00"){
		updateInfoA="key_appid,02|key_sdate,"+idate;
		blnRs=updateBaseInfo(adf,updateInfoA);//0015
		if(!blnRs){
			checkError(getError());
			return false;
		}
		//9A00 16文件暂时不更新
	}
	
	if(appFlag=="M1BK"){
		var findM1Flag = findLogicCard();
		var flag = true;
		if(findM1Flag){
			var cardsnInfo = readBlockExternal(initKey,0,0,0);
			
			var cardsn = cardsnInfo.substring(0,8);
			console.log("cardsn==>"+cardsn);
			var mode = citizenCardNo.substr(0, 2)=="11"?modeB:modeA;
			$("input[name='cardsnByOpenApp']").val(cardsn);
			var params = {"citizenCardNo":citizenCardNo,"appType":appType,"cardsn":cardsn,"appFlag":appFlag};
			//发送后台
			$.ajax({
				type: 'POST',
				url:"appOpenReg/appOpenToWriteCard",
				dataType:"json",
				data:params,
				async: false,
				success:function(json){
					if(json.statusCode==DWZ.statusCode.ok){
						var keys=json.key;
						var data=json.data;
						if(keys.length>0&&data.length>0){
							for(var i=0;i<keys.length;i++){
								//格式化扇区密钥(模式4)
								var sector=parseInt(keys[i].no);
								var writeInfo=keys[i].keya+keys[i].contrlword+keys[i].keyb;
								//20190215 修改以下一行    模式4改为0
								var f= WriteBlockExternal(initKey,sector,sector*4+3,0,writeInfo);
								if(!f){
									alertMsg.warn("自行车应用M1格式化扇区失败");
									checkError(getError());
									flag=false;
									return false;
								}
							}
							for(var j=0;j<data.length;j++){
								var sector2=parseInt(data[j].no);
								for(var i=0;i<keys.length;i++){
									var sector=parseInt(keys[i].no);
									if(sector==sector2){
										//写扇区(模式0)
										var ff= writeSectorExternal(keys[i].keya,sector2,0,data[i].data);
										if(!ff){
											alertMsg.warn("自行车应用M1写扇区失败");
											checkError(getError());
											flag=false;
											return false;
										}
									}
								}		
							}
						}
					}else{
						navTabAjaxDone(json);
						//20190225 hgl 增加以下1行
						flag=false;
					}					
				},
				error: DWZ.ajaxError
			})	
			//终止提交
			if(!flag){
				return false;
			}
			if(flag){
				$("#pagerFormByOpenApp").attr("action","appOpenReg/openBikeAppRegister");
				$("#pagerFormByOpenApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
			}
		}else{
			checkError(getError());
			return false;
		}
	}
	if(appFlag=="TSYY"){
		$("#pagerFormByOpenApp").attr("action","appOpenReg/openLibAppRegister");
		$("#pagerFormByOpenApp").attr("onsubmit","return validateCallback(this,printViewPageAjaxDone);");
	}
	return flag;
}

